{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'BP0btXKGGNki1HzFl8nYy9gS'\n",
    "SECRET_KEY = 'hddu9H4TUzUzvOIe8bhxUMLNpqZ5fQT6'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "from urllib.request import urlopen\n",
    "from urllib.request import Request\n",
    "from urllib.error import URLError\n",
    "from urllib.parse import urlencode\n",
    "timer = time.perf_counter\n",
    "SCOPE = 'audio_voice_assistant_get' \n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "# 获取access_token\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "#     print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#     print(result)\n",
    "    \n",
    "    if ('access_token' in result.keys()):\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\n",
    "def asr(token,AUDIO_FILE='1.wav',CUID='123456PYTHON',RATE=16000,DEV_PID=1537):\n",
    "    speech_data = []\n",
    "    # 打开目标语音文件\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {\n",
    "        'cuid': CUID, \n",
    "        'token': token, \n",
    "        'dev_pid': DEV_PID\n",
    "    }\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "    FORMAT=AUDIO_FILE[-3:]\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = 'http://vop.baidu.com/server_api' + \"?\" + params_query\n",
    "    SCOPE = 'audio_voice_assistant_get' \n",
    "    # print post_data\n",
    "    req = Request('http://vop.baidu.com/server_api' + \"?\" + params_query, speech_data, headers)\n",
    "    # 异常处理，避免出现红色的bug（提前预判可能出现的异常）\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    #         print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8') # result_str 已经是字符串（字典）\n",
    "    #    print(eval(result_str)[\"result\"][0][:-1]) # eval()将str --> dict\n",
    "#     print(qa.get(eval(result_str)[\"result\"][0][:-1]))\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.4225dbc2e0e351ba3dfdc378d803f9c8.2592000.1655381883.282335-26256004'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7098679350723652166\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"141434576621652790081\"}\\n'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr(xu_token,'/Users/dapangxiaren/Documents/speech-demo-master/rest-api-asr/python/audio/16k.wav')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: SpeechRecognition in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (3.8.1)\r\n"
     ]
    }
   ],
   "source": [
    "!pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: pipwin in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (0.5.2)\n",
      "Requirement already satisfied: js2py in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (0.71)\n",
      "Requirement already satisfied: requests in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (2.27.1)\n",
      "Requirement already satisfied: pyprind in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (2.11.3)\n",
      "Requirement already satisfied: docopt in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (0.6.2)\n",
      "Requirement already satisfied: pySmartDL>=1.3.1 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (1.3.4)\n",
      "Requirement already satisfied: packaging in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (21.3)\n",
      "Requirement already satisfied: six in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (1.16.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pipwin) (4.10.0)\n",
      "Requirement already satisfied: soupsieve>1.2 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.3.1)\n",
      "Requirement already satisfied: pyjsparser>=2.5.1 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from js2py->pipwin) (2.7.1)\n",
      "Requirement already satisfied: tzlocal>=1.2 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from js2py->pipwin) (4.2)\n",
      "Requirement already satisfied: backports.zoneinfo in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from tzlocal>=1.2->js2py->pipwin) (0.2.1)\n",
      "Requirement already satisfied: pytz-deprecation-shim in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from tzlocal>=1.2->js2py->pipwin) (0.1.0.post0)\n",
      "Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from packaging->pipwin) (3.0.4)\n",
      "Requirement already satisfied: tzdata in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from pytz-deprecation-shim->tzlocal>=1.2->js2py->pipwin) (2022.1)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from requests->pipwin) (1.26.8)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from requests->pipwin) (3.3)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from requests->pipwin) (2.0.4)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/dapangxiaren/opt/anaconda3/lib/python3.8/site-packages (from requests->pipwin) (2021.10.8)\n",
      "Usage:\n",
      "  pipwin install (<package> | [-r=<file> | --file=<file>]) [--proxy=<proxy>]\n",
      "  pipwin uninstall <package>\n",
      "  pipwin download (<package> | [-r=<file> | --file=<file>]) [-d=<dest> | --dest=<dest>] [--proxy=<proxy>]\n",
      "  pipwin search <package> [--proxy=<proxy>]\n",
      "  pipwin list\n",
      "  pipwin refresh [--log=<log>] [--proxy=<proxy>]\n",
      "  pipwin (-h | --help)\n",
      "  pipwin (-v | --version)\n"
     ]
    }
   ],
   "source": [
    "!pip install pipwin\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Usage:\r\n",
      "  pipwin install (<package> | [-r=<file> | --file=<file>]) [--proxy=<proxy>]\r\n",
      "  pipwin uninstall <package>\r\n",
      "  pipwin download (<package> | [-r=<file> | --file=<file>]) [-d=<dest> | --dest=<dest>] [--proxy=<proxy>]\r\n",
      "  pipwin search <package> [--proxy=<proxy>]\r\n",
      "  pipwin list\r\n",
      "  pipwin refresh [--log=<log>] [--proxy=<proxy>]\r\n",
      "  pipwin (-h | --help)\r\n",
      "  pipwin (-v | --version)\r\n"
     ]
    }
   ],
   "source": [
    "!pipwin instll PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
